import urllib2
import re
import logging

def convert_swf_to_images(swf): 
    logging.debug('Upload to swiffy.')
    content_type, body = encode_multipart_formdata(swf)
    f = urllib2.urlopen(urllib2.Request('http://swiffy.googlelabs.com/upload', body,  {'Content-Type': content_type,
               'Content-bufferength': len(body)}))
    res = f.read()
    if not res:
        raise RuntimeError('No response from swiffy website.', str(f.info()))
    logging.debug('Response from swiffy : %s' % res)
    m = re.search(r',"(\w+\.html)","(http://swiffylabs.googleusercontent.com/view/o/.*/)"', res)
    if m is None:
        raise RuntimeError('Wrong result from swiffy website.')
    html_url = m.group(2) + m.group(1)
    logging.debug('Uploaded html : %s' % html_url)
    html = urllib2.urlopen(html_url).read()
    result = [] 
    for type, data in re.findall('"data":"data:(image/\w+);base64,([A-Za-z0-9+/=\s]+)', html.replace('\\n','')):
        result.append({'type': type, 'data': data, 'encoding': 'base64'})
    logging.debug('Found %d images' % len(result))
    return result

def encode_multipart_formdata(swf):
    boundary ='----------ThIs_Is_tHe_bouNdaRY_$' 
    buffer = []
    buffer.append('--' + boundary)
    buffer.append('Content-Disposition: form-data; name="swfFile"; filename="cor8.swf"')
    buffer.append('Content-Type: application/x-shockwave-flash')
    buffer.append('')
    buffer.append(swf)
    buffer.append('--' + boundary + '--')
    buffer.append('')
    return 'multipart/form-data; boundary=%s' % boundary, '\r\n'.join(buffer)